﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using Microsoft.Kinect;
using System.Windows;
using System.Threading;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace kinectSocketController
{
    public class Client
    {
        static byte[] receive = new byte[1024];

        static Socket clientSocket;
        public Client()
        {
            //设定服务器IP地址  
            IPAddress ip = IPAddress.Parse("192.168.125.12");
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.BeginConnect(new IPEndPoint(ip, 13000), new AsyncCallback(ConnectCallback), clientSocket); //配置服务器IP与端口  
                Console.WriteLine("连接服务器成功");
            }
            catch
            {
                Console.WriteLine("连接服务器失败，请按回车键退出！");
                return;
            }
        }
         ~Client() {
            clientSocket.Close();
        }
        static void ConnectCallback(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;
            socket.EndConnect(ar);
            socket.BeginReceive(receive, 0, receive.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
        }
        static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                Socket socket = (Socket)ar.AsyncState;
                int reLength = socket.EndReceive(ar);
                string reString = Encoding.UTF8.GetString(receive, 0, reLength);
                socket.BeginReceive(receive, 0, receive.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
            }
            catch
            {
            }

        }
        public void SendCallback(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;
            socket.EndSend(ar);
        }
        public Boolean send(Object obj)
        {
            CmdObj cmdObj = (CmdObj)obj;
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(ms, cmdObj);
                    byte[] bytes2send = ms.GetBuffer();
                    clientSocket.BeginSend(bytes2send, 0, bytes2send.Length, SocketFlags.None, new AsyncCallback(SendCallback), clientSocket);
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
    }
}